package com.zjut.an.util.tools;

import java.sql.Timestamp;  
import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.sf.ezmorph.MorphException;  
import net.sf.ezmorph.object.AbstractObjectMorpher;  
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

public class JSONUtilClassTime  extends AbstractObjectMorpher {
	/*** 日期字符串格式 */
	private String[] formats;

	public static Object getDTO(String json, Class clazz){  
	    String[] formats={"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};  
	    JSONUtils.getMorpherRegistry().registerMorpher(new JSONUtilClassTime(formats));  
	    JSONObject jsonObject=JSONObject.fromObject(json);  
	    return JSONObject.toBean(jsonObject,clazz);  
	}
	
	public static List getDTOList(String jsonString, Class clazz) {
		String[] formats={"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};  
	    JSONUtils.getMorpherRegistry().registerMorpher(new JSONUtilClassTime(formats)); 
		JSONArray array = JSONArray.fromObject(jsonString);
		List list = new ArrayList();
		for (Iterator iter = array.iterator(); iter.hasNext();) {
			JSONObject jsonObject = (JSONObject) iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz));
		}
		return list;
	}
	
	public JSONUtilClassTime(String[] formats) {
		this.formats = formats;
	}

	public Object morph(Object value) {
		if (value == null) {
			return null;
		}
		if (Timestamp.class.isAssignableFrom(value.getClass())) {
			return (Timestamp) value;
		}
		if (!supports(value.getClass())) {
			throw new MorphException(value.getClass() + " 是不支持的类型");
		}
		String strValue = (String) value;
		SimpleDateFormat dateParser = null;
		for (int i = 0; i < formats.length; i++) {
			if (null == dateParser) {
				dateParser = new SimpleDateFormat(formats[i]);
			} else {
				dateParser.applyPattern(formats[i]);
			}
			try {
				return new Timestamp(dateParser.parse(strValue.toLowerCase())
						.getTime());
			} catch (ParseException e) {
				// e.printStackTrace();
			}
		}
		return null;
	}
	
	@Override  
	public Class morphsTo() {
		return Timestamp.class;
	}

	public boolean supports(Class clazz) {
		return String.class.isAssignableFrom(clazz);
	}
	
	
}
